<template>
  <div>
    <ElDialog
      :model-value="DialogShow"
      :title="title"
      :before-close="handleClose"
      :destroy-on-close="true"
      v-if="type != 'wizard' && type != 'importData'"
    >
      <ElementForm
        ref="myform"
        :loadKey="form.loadKey"
        :formFields="form.formFields"
        :formRules="form.formRules"
        :labelWidth="labelWidth"
        @update:value="hanldFromData"
      >
        <div style="text-align: center">
          <ElButton type="primary" :loading="loadingIcon" @click="getForm">提交</ElButton>
          <ElButton @click="reset">重置表单</ElButton>
        </div>
      </ElementForm>
    </ElDialog>
    <ElDialog
      :model-value="DialogShow"
      :title="title"
      :before-close="handleClose"
      :destroy-on-close="true"
      v-else-if="type == 'importData'"
    >
      <ElementForm
        ref="myform"
        :loadKey="form.loadKey"
        :formFields="form.formFields"
        :formRules="form.formRules"
        :labelWidth="labelWidth"
        @update:value="hanldFromData"
      >
        <div style="text-align: center">
          <ElButton type="primary" :loading="loadingIcon" @click="submitImport">提交</ElButton>
          <ElButton @click="resetImport">重置表单</ElButton>
        </div>
      </ElementForm>
    </ElDialog>
    <ElDialog
      :model-value="DialogShow"
      :title="title"
      width="60%"
      :before-close="handleClose"
      :destroy-on-close="true"
      v-else
    >
      <ElementWizardForm
        @update:value="hanldFromWizard"
        :regionIdZList="regionIdZList"
        :regionId="regionId"
        :dataTree="dataTree"
      />
    </ElDialog>
    <ElDialog
      :model-value="treePermission"
      title="选择数据权限"
      width="60%"
      :before-close="handleClosePermission"
      :destroy-on-close="true"
    >
      <LeftTree :data="data" :islower="true" />
    </ElDialog>
    <ElDialog
      :model-value="treeExportData"
      title="导出单元"
      width="500px"
      style="height: 70%"
      :before-close="handleCloseExportData"
      :destroy-on-close="true"
      class="export-data"
    >
      <ElTree
        ref="treeRef"
        :data="TreeList"
        show-checkbox
        node-key="id"
        highlight-current
        :props="nodePops"
        :default-expanded-keys="treeExpandData"
      />
      <template #footer>
        <div class="dialog-footer buttons" style="text-align: center">
          <ElButton type="primary" @click="submitExportData" :loading="submitLoading"
            >提交</ElButton
          >
          <ElButton @click="resetExportData">重置</ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ElTree } from 'element-plus';
  import { useRoute } from 'vue-router';
  import useLoading from '@/hooks/loading';
  import { regionidzType } from '@/types';
  import qs from 'qs';
  import { throttle } from 'lodash-es';
  import { form, treePermission, treeExportData, TreeList } from '../LeftTree/index';
  import { getUnitSave, getdomainList, exportUnit, ImportUnit } from '@/api/Unitregein/index';
  const { loadingIcon, setLoading } = useLoading();
  const myform = ref<any>(null);
  const title = ref<string>('');
  const type = ref<string>('');
  const submitData = ref<Namespace.UnitObjectSaveUp>({});
  const numberValue = ref<number>(1);
  const DialogShow = ref<boolean>(false);
  const submitLoading = ref<boolean>(false);
  const Route = useRoute();
  const parameter = ref<string>('');
  const regionIdZList = ref<Array<regionidzType>>();
  const labelWidth = ref<number>(110);
  const emit = defineEmits<Emits>();
  interface Emits {
    (e: 'update:value', val: boolean): void;
  }
  // const myformImport = ref<any>(null);
  const treeRef = ref<InstanceType<typeof ElTree>>();
  const treeExpandData = ref<Array<string>>([]);
  const nodePops = {
    value: 'id',
    label: 'text',
    children: 'children',
  };
  const props = defineProps({
    type: {
      type: String,
      default: '',
    },
    show: {
      type: Boolean,
      default: false,
    },
    dataTree: {
      type: String,
      default: '',
    },
    regionId: {
      type: Number,
    },
    unitType: {
      type: String,
      default: '',
    },
  });
  const data = reactive<any>({
    dataId: {},
    regionId: 0,
    update: 0,
    selected: null,
  });
  onMounted(() => {
    switch (Route.name) {
      case 'root':
        parameter.value = '1';
        break;
      case 'sourceDataManage':
        parameter.value = '0';
        break;
      case 'enumErationDomain':
        parameter.value = '2';
        break;
      case 'cataAccess':
        parameter.value = '3';
        labelWidth.value = 120;
        break;
      case 'sqlManagement':
        parameter.value = '4';
        break;
      default:
        break;
    }
  });
  watch(
    () => props,
    async (val) => {
      DialogShow.value = props.show;
      type.value = props.type;
      const { data } = await getdomainList('0');
      const dataList = data.map((it) => {
        return {
          value: it.regionCode + '(' + it.regionName + ')',
          key: it.regionId as number,
        };
      });
      form.formRules &&
        form.formRules.map((it) => {
          it.filter(async (item) => {
            if (item.field == 'dataId') {
              item.data = dataList;
            }
          });
        });
      regionIdZList.value = dataList;
      // DomainList.value = dataList as unknown as Array<Namespace.RegionObject>;
      switch (val.type) {
        case 'group':
          title.value = '新增包';
          break;
        case 'unit':
          title.value = '新增单元';
          break;
        case 'list':
          title.value = '新增列表';
          break;
        case 'query':
          title.value = '新增查询';
          break;
        case 'table':
          title.value = '新增表';
          break;
        case 'wizard':
          title.value = '快速页面';
          break;
        case 'enum':
          title.value = '新增枚举';
          break;
        case 'assignmentSql':
          title.value = '新增赋值sql';
        case 'verifySql':
          title.value = '新增验证sql';
        case 'exportData':
          title.value = '导出单元';
        case 'importData':
          title.value = '导入单元';
        default:
          break;
      }
    },
    {
      deep: true,
    },
  );
  watch(TreeList, () => {
    treeExpandData.value = TreeList.value ? [TreeList.value[0].id] : [];
  });
  const sendHandleSelectCommand = async (value) => {
    form.formFields.rightdataName = value.text;
    form.formFields.rightdataId = value.id;
    treePermission.value = false;
  };
  provide('sendHandleSelectCommand', sendHandleSelectCommand);
  const handleClose = () => {
    emit('update:value', false);
    myform.value.reset();
  };
  const hanldFromWizard = (value: boolean) => {
    emit('update:value', value);
  };
  const sendUpTreeData = inject('sendUpTree') as Function;
  const getForm = throttle(async () => {
    myform.value.validate();
    numberValue.value++;
    await setTimeout(async () => {
      setLoading(true);
      if (myform.value.success) {
        submitData.value.unitType = props.unitType as unknown as number;
        submitData.value.regionId = props.regionId;
        submitData.value.parentId = props.dataTree as unknown as number;
        try {
          const { code } = await getUnitSave(qs.stringify(submitData.value));
          if (code == 0) {
            setTimeout(() => {
              sendUpTreeData({ numberValue: numberValue.value, id: props.dataTree, code: 0 });
              DialogShow.value = false;
              myform.value.reset();
              emit('update:value', false);
            }, 500);
          }
        } catch (error) {
          setLoadingFalse();
        } finally {
          setLoadingFalse();
        }
      }
      setLoadingFalse();
    });
  });
  const setLoadingFalse = () => {
    setTimeout(() => {
      setLoading(false);
    }, 500);
  };
  const reset = async () => {
    // let data = {};
    // myform.value.reset(data);
    await setTimeout(() => {
      myform.value.reset();
    });
  };
  const hanldFromData = async (value: Object) => {
    submitData.value = value;
  };
  const handleClosePermission = () => {
    treePermission.value = false;
  };
  // const handleCloseImortData = () => {
  //   treeImortData.value = false;
  //   emit('update:value', false);
  //   myformImport.value.reset();
  // };
  const resetImport = async () => {
    await setTimeout(() => {
      myform.value.reset();
      myform.value.fileRemove2();
    });
  };
  const submitImport = throttle(async () => {
    myform.value.validate();
    const f = myform.value.getFile();
    if (f.value == undefined) {
      ElMessage.error('请上传文件');
      return false;
    }
    numberValue.value++;
    await setTimeout(async () => {
      if (!myform.value.success) {
        return false;
      }
      let formData = new FormData();
      formData.append('file', f.value.raw);
      formData.append('dataId', submitData.value.dataId?.toString() || '');
      formData.append('cover', submitData.value.cover?.toString() || '0');
      formData.append('regionId', props.regionId?.toString() || '');
      const { code } = await ImportUnit(formData);
      if (code == 0) {
        setTimeout(() => {
          sendUpTreeData({ numberValue: numberValue.value, id: props.dataTree, code: 0 });
          DialogShow.value = false;
          myform.value.reset();
          emit('update:value', false);
        }, 500);
      }
    });
  });

  const handleCloseExportData = () => {
    treeExportData.value = false;
  };
  const resetExportData = () => {
    treeRef.value!.setCheckedKeys([], false);
  };
  const getTreeData = (checkedKeys) => {
    const getCheckedNodes = (nodes) => {
      return nodes
        .filter((node) => checkedKeys.includes(node.id))
        .map((node) => {
          if (node.children) {
            return {
              id: node.id,
              children: getCheckedNodes(node.children),
            };
          }
          return node;
        });
    };
    return getCheckedNodes(TreeList.value);
  };
  const submitExportData = () => {
    const checkedKeys = [
      ...treeRef.value!.getHalfCheckedKeys(),
      ...treeRef.value!.getCheckedKeys(),
    ];
    if (!checkedKeys.length) {
      ElMessage.error('请先选择需要导出的单元');
      return false;
    }
    console.log('选中数据 树形结构', getTreeData(checkedKeys));
    setTimeout(async () => {
      try {
        submitLoading.value = true;
        await exportUnit({
          ids: getTreeData(checkedKeys)[0].children,
        });
        submitLoading.value = false;
        // if (code == 0) {
        //   setTimeout(() => {
        //     treeExportData.value = false;
        //   }, 500);
        // }
      } catch (error) {
        console.log(error);
        setLoadingFalse();
      } finally {
        setLoadingFalse();
      }
    });
  };
</script>

<style lang="scss" scoped>
  :deep(.el-dialog) {
    overflow: hidden;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
  }
  :deep(.el-dialog__title) {
    color: var(--el-color-white);
  }
  :deep(.export-data) {
    .el-dialog__body {
      height: calc(100% - 112px);
      overflow: auto;
    }
  }
</style>
